package excerciceATM;

public class ATM {
	
	private boolean userAuthenticated;
	private int currentAccountNumber;
	private Screen screen;
	private Keypad keypad;
	private CashDispenser cashDispenser;
	private DepositSlot depositSlot;
	private BankDatabase bankDatabase;
	
	private static final int balance_inuiry = 1;
	private static final int withdrawl = 2;
	private static final int deposit = 3;
	private static final int exit = 4;
	
	public ATM() {
		userAuthenticated = false;
		currentAccountNumber = 0;
		screen = new Screen();
		keypad = new Keypad();
		cashDispenser = new CashDispenser();
		bankDatabase = new BankDatabase();
	}
	
	public void run() {
		
		while ( true ) {
			
			while ( !userAuthenticated ) {
				screen.displayMessageLine("\nWelcome!");
				authenticateUser();
			}
			
			performTransactions();
			userAuthenticated = false;
			currentAccountNumber = 0;
			screen.displayMessageLine("\nThank you! Goodbye!");
		}
	}
	
	public void authenticateUser() {
		screen.displayMessage("\nPlease enter your account number");
		int accountNumber = keypad.getInput();
		screen.displayMessage("\nEnter your pin: ");
		int pin = keypad.getInput();
		
		userAuthenticated = bankDatabase.authenticateUser( accountNumber, pin );
		
		if ( userAuthenticated ) {
			currentAccountNumber = accountNumber;			
		} else {
			screen.displayMessageLine("Invalid account number or PIN. Please try again");
		}
	}
	
	public void performTransactions() {
		Transaction currentTransaction = null;
		
		boolean userExisted = false;
		
		while ( !userExisted ) {
			int mainMenuSelection = displayMainMenu();
			
			switch (mainMenuSelection) {
			
				case balance_inuiry:
				case withdrawl:
				case deposit:
					currentTransaction = createTransaction( mainMenuSelection );
					currtentTransaction.execute();
					break;
				case exit:
					screen.displayMessageLine("\nExiting the system...");
					userExisted = true;
					break;
				default:
					screen.displayMessageLine("\nYou did not enter a valid selection. Try again");
					break;
			}
		}
	}
	
	private int displayMenu() {
		screen.displayMessageLine("znMain menu");
		screen.displayMessageLine("1 - View my balance");
		screen.displayMessageLine("2 - Withdraw cash");
		screen.displayMessageLine("3 - Deposit funds");
		screen.displayMessageLine("4 - Exit");
		screen.displayMessageLine("Enter a choice: ");
		return keypad.getInput();
	}
	
	public Transaction createTransaction( int type ) {
		Transaction temp = null;
		
		switch ( type ) {
		case balance_inuiry:
			temp = new BalaceInauiry( currentAccountNumber, screen, bankDatabase );
			break;
		case withdrawl:
			temp = new Withdrawl( currentAccountNumber, screen, bankDatabase, keypad, cashDispenser );
			break;
		case deposit:
			temp = new Deposit( currentAccountNumber, screen, bankDatabase, keypad, depositSlot );
			break;
		}
		
		return temp;
	}
	
}
